class Megaupload < Link
  def initialize(link)
    super(link)
		@cookie=""
    @log=@@logs["Megaupload"]
    @conf=@@conf["Megaupload"]
    @header={
      'User-Agent'=>'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.5) Gecko/2008120121 Firefox/3.0.5',
      'Accept'=>'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
      'Accept-Language'=>'en-us,en;q=0.5',
      'Accept-Encoding'=>'gzip,deflate',
      'Accept-Charset'=>'ISO-8859-1,utf-8;q=0.7,*;q=0.7',      
      'Keep-Alive'=>'300',
      'Connection'=>'keep-alive'
    }
	end
  def download()
    
    @log.info("downloading link #{@link} in free mode")
    return free_download
      
  end
  def free_download()
    @log.info("Downloading #{@link}")
    link1=URI.escape(@link," '[]")
    url=URI.parse(link1)
    http1 = Net::HTTP.start(url.host, 80)
    resp, data = http1.get(url.path+"?"+url.query)    
    q=url.query.gsub("d=","")
    #dump_html("megaupload_#{q}_paso01",data)
    
    if resp.message == "OK"
      
      again=data.scan(/Please check back in (\d+) minutes/)
      if(!again.empty?)
        @log.info("#{@link} error try again in #{again[0][0]} minutes")
        return again[0][0].to_i*60
      end
      
      captcha,megavar,imagecode=[]      
      captchacode=data.scan(/captchacode\".*?value=\"(.*)"\>/)      
      captcha=data.scan(/src=\"http:\/\/(.+.megaupload.com)\/gencap.php\?([0-9a-zA-Z]+).gif\"/)      
      megavar=data.scan(/megavar\".*?value=\"([0-9a-zA-Z]+)\"/)      
      
      if captcha.empty? or megavar.empty? or captchacode.empty?
        return 5 # wait 5 seconds and try again
      end           
      
      gif=captcha[0][1]+".gif"
      tif=captcha[0][1]+".tif"
      txt=captcha[0][1]
    
      httpcap = Net::HTTP.start(captcha[0][0], 80)
      resp2, data2= httpcap.get("/gencap.php?"+gif)
      if resp2.message == "OK"
         giffile=File.join($conf["main"]["tmp_dir"],"captcha_#{gif}")
         file=open(giffile, "wb")
         file.write(data2)
         file.close
      else
         return 10
      end      
      tiffile=File.join($conf["main"]["tmp_dir"],"captcha_#{tif}")
      capfile=File.join($conf["main"]["tmp_dir"],"captcha_#{txt}")
      #reoslv captcha
      #TODO sanity check!!!! this is very very dengerous!!!
      convert="convert #{giffile} -depth 8 -alpha off #{tiffile}"
      tesseract="tesseract #{tiffile} #{capfile}"
      #puts convert
      #puts tesseract
      
      if !(system(convert) and system(tesseract))
        msg="can not resolve captcha for #{@link} trying again in 10 seconds"
        puts msg
        @log.info(msg)
        return 10
      end
      #File.exist?("#{capfile}.txt")
      str=File.open("#{capfile}.txt").read(4)
      #system("rm -f #{capfile}.txt #{giffile} #{tiffile}")
      puts str
      post="megavar=#{megavar[0][0]}&captchacode=#{captchacode[0][0]}&captcha=#{str}"
      resp3, data3 = http1.post(url.path+"?"+url.query,post)
      #dump_html("megaupload_#{q}_paso02",data3)
      
      if resp3.message == "OK"         
        dllink=data3.scan(/id=\"downloadlink\">\s*<a\s*href=\"(http:\/\/www....megaupload.com\/.+)\"\s*onclick=\"\"\>/)
        if !(dllink.empty?)
          dllink_final=dllink[0][0]
          puts dllink_final          
          waiting=data3.scan(/count=(\d+);/)[0][0].to_i+5          
          self.wait(waiting.to_i)
          download_link(dllink_final)
          @log.info("#{dllink_final} downloaded in #{@time_elapsed}")
          return 0
        else
          puts "link no encontrado"
          return 10
        end
      else
        puts "bad response"
        return 10
      end        
	   end
	end
  
  #is a megaupload link
  def Megaupload.is_link?(link)
    if Link.is_link?(link,"www.megaupload.com")
      true
    else
      false
    end
  end
  
	def check_link(link=nil)
    link=@link unless link
    link=URI.escape(link," '[]")
    url=URI.parse(link)
		http = Net::HTTP.start(url.host, 80)
    resp, data = http.get(url.path+"?"+url.query,@header)		
    dump_html(url.query+"_check",data)
		if resp.message == "OK"
			begin        
        if link =~ /http:\/\/www.megaupload.com\/.*/
            if not (data.scan(/captchaform/).empty?)
              @log.info("Link OK: #{link}")
              return true
            else              
              @log.info("Bad Link: #{link}")
              return false
            end
        end
		  	rescue StandardError=>error				 		
        @log.info("Bad Link: #{link}")
		 		return false
      end
    else      
      @log.info("Bad Link: #{link}")
		 	return false
		end
	end
  def parallel_downloads()
    case @conf["type"]
      when "free"        
        return 1
      when "premium"
        return @conf["parallel_downloads"].to_i
    end    
  end
end